﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using Microsoft.SharePoint.Utilities;
using SharePointees.EnhancedLookupField.Tools.Trace;
using System.Web.UI;
using System.Web;

namespace SharePointees.EnhancedLookupField.Tools
{
    public static class SPTools
    {
        private const string APP_NAME = "EnhancedLookupField";

        #region HP Site

        /// <summary>
        /// Returns an Elevated privilege SPSite
        /// </summary>
        /// <param name="url">Site URL</param>
        /// <returns></returns>
        public static SPSite GetHPSite(string url)
        {
            SPSite HPSite = null;
            using (SPSite site = new SPSite(url))
            {
                HPSite = new SPSite(url, GetSystemToken(site));
            }
            return HPSite;
        }

        /// <summary>
        /// Extends SPWeb Type in order to get a high privilege SPSite
        /// </summary>
        /// <param name="web"></param>
        /// <returns></returns>
        public static SPSite GetHPSite(this SPWeb web)
        {
            return GetHPSite(web.Site.Url);
        }
        
        /// <summary>
        /// Extends SPSite type in order to get a high privilege SPSite
        /// </summary>
        /// <param name="site"></param>
        /// <returns></returns>
        public static SPSite GetHPSite(this SPSite site)
        {
            return GetHPSite(site.Url);
        }

        /// <summary>
        /// Returns the admin user token
        /// </summary>
        /// <param name="site"></param>
        /// <returns></returns>
        public static SPUserToken GetSystemToken(SPSite site)
        {
            SPUserToken token = null;
            bool tempCADE = site.CatchAccessDeniedException;
            try
            {
                site.CatchAccessDeniedException = false;
                token = site.SystemAccount.UserToken;
            }
            catch (UnauthorizedAccessException)
            {
                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    using (SPSite elevSite = new SPSite(site.ID))
                        token = elevSite.SystemAccount.UserToken;
                });
            }
            finally
            {
                site.CatchAccessDeniedException = tempCADE;
            }
            return token;
        }

        #endregion

        #region SPList


        /// <summary>
        /// Returns a list from a SPWeb, using a relative url
        /// </summary>
        /// <param name="UrlListWebRelative">List's relative url (ex: '/Lists/Contacts')</param>
        /// <param name="web"></param>
        /// <returns></returns>
        public static SPList GetListByWebRelativeUrl(this SPWeb web, string UrlListWebRelative)
        {
            string webRelativeUrl = web.ServerRelativeUrl;
            SPList requestedList = null;
            try
            {
                 requestedList = web.GetList(SPUrlUtility.CombineUrl(webRelativeUrl, UrlListWebRelative));
            }
            catch (FileNotFoundException listNotFound)
            {
                TraceManager.WriteError(APP_NAME, listNotFound);
            }
            return requestedList;
        }


        #endregion

#region Resources

        /// <summary>
        /// Get a ressource from 12/ressources/
        /// </summary>
        /// <param name="resourceKey"></param>
        /// <returns></returns>
        public static string GetResourcesFrom12(SPWeb web, string resourceKey, string resourceFile)
        {
            string value = string.Empty;
            try
            {
                value = SPUtility.GetLocalizedString(string.Format("$Resources:{0}", resourceKey), resourceFile, web.Language);
            }
            catch(Exception ex)
            {
                TraceManager.WriteError(APP_NAME, ex);
            }
            return value;
        }

        /// <summary>
        /// Get a ressource from 12/ressources/
        /// </summary>
        /// <param name="resourceKey"></param>
        /// <returns></returns>
        public static string GetResourcesFromHttpContext(SPWeb web, string resourceKey, string resourceFile)
        {
            string value = string.Empty;
            if (HttpContext.Current == null)
                throw new NullReferenceException();
            try
            {
                value = HttpContext.GetGlobalResourceObject(resourceFile, resourceKey).ToString();
            }
            catch (Exception ex)
            {
                TraceManager.WriteError(APP_NAME,ex);
            }
            return value;
        }

#endregion

        #region AJAX Fix

        public static void FixMOSSAjax(UserControl uc)
        {
            FixMOSSAjax(uc.Page);
        }

        /// <summary>
        /// Fix multi postback problems with ajax using MOSS 2007
        /// </summary>
        public static void FixMOSSAjax(Page p)
        {
            if (p.Form != null)
            {
                if (p.Form.Attributes["onsubmit"] == "return _spFormOnSubmitWrapper();")
                    p.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
            }

            p.ClientScript.RegisterStartupScript(p.GetType(), "UpdatePanelFix", "_spOriginalFormAction = document.forms[0].action;_spSuppressFormOnSubmitWrapper=true;", true);
        }

        #endregion
    }
}
